<?php
/**
 * @filesource:					NodeAction.class.php
 * @desc:						操作节点模块模型类
 * 
 * @author:						houyining
 * @copyright:					hou.yining@gmail.com	
 * @date:						2011-04-12
 */

class NodeModel extends Model {
	protected $_validate	=	array(
		array('name','checkNode','节点已经存在',0,'callback'),
		array('name', 'require', '节点名不能为空 ！'),
		array('title', 'require', '节点标题不能为空！'),
		array('sort', 'require', '排序值不能为空！'),
		array('sort', 'number', '排序值必须是数字！'),
		);
	
	protected $_auto = array(
		array('status', 1),
	);
	
	public function checkNode() {
		$map['name']	 =	 $_POST['name'];
		$map['pid']	=	isset($_POST['pid'])?$_POST['pid']:0;
        $map['status'] = 1;
        if(!empty($_POST['id'])) {
			$map['id']	=	array('neq',$_POST['id']);
        }
		$result	=	$this->where($map)->field('id')->find();
        if($result) {
        	return false;
        }else{
			return true;
		}
	}
	
	public function getRootNodeId(){
		$list = $this->where(array('level'=>1))->field('id')->find();
		return $list['id'];
	}
	
	public function getRootNodeLevel(){
		return 1;
	}
	
	public function getLevel($parent_id){
		$list = $this->where(array('id'=>$parent_id))->field('level')->find();
		return $list['level'] + 1;
	}
	
	//获取权限树
	//暂时获取二级节点树
	public function getNodeTree($node_id = ''){
		if($node_id == ''){
			$node_id = $this->getRootNodeId();
		}
		$root_level = $this->getRootNodeLevel();
		
		$level_1_nodes = $this->where('level='.($root_level+1).' and pid='.$node_id)->order('sort')->select();
		
		$node_tree = array();
		foreach($level_1_nodes as  $node){
			$node_tree[$node['id']] = $node;
			$node_tree[$node['id']]['child'] = array();
			$level_2_nodes = $this->where('level='.($root_level+2).' and pid='.$node['id'])->order('sort')->select();
			if($level_2_nodes != NULL){
				$node_tree[$node['id']]['child'] = $level_2_nodes;
			}
		}
		
		return $node_tree;
	}
}
?>